<?php

class serviceModel extends commonModel {


    public function __construct() {
        $this->initialDB();
    }

    # 指派 门店编号+运单编号+指派ID
    public function send_order($order){
        $config = Config::getInstance();
        $website_array = $config->getWebSiteConfig();

        $sendorder_result=array("result_code"=>"-1","express_code"=>'-1',"express_code_desc"=>'接口失败');
        $log=new Logging();
        $log->lfile('push_express_order');

        foreach($order as $k=>$v){
            $data_id = $this->addExpressData($v, 2);  //建立指派订单
            #顺丰
            if ($v['express_type'] == "sf"){
                $sfe = new SFExpressClass($website_array['debug'],$v['company']['sf_dev_key'],$v['company']['sf_dev_id'],$v['company']['sf_user_name']);
                $info = $sfe->send_parameter($v);
                if(is_array($info)) {
                    $info = array_merge($info, $sendorder_result);
                }
                $log->lwrite($v['shop_express_no'].'=>sf推送结果:'.json_encode($info, JSON_UNESCAPED_UNICODE));
                if($info && $info['error_code'] == 0){   //推送成功
                    $_result=array();
                    $_result['shop_express_no']=$info['result']['shop_order_id'];
                    $_result['express_order_no']=$info['result']['sf_order_id'];
                    $_result['express_fee'] = $info['result']['total_price']/100;
                    $this->push_success($_result, $info);

                    //for express_data
                    $info['result_code']=0;
                    $info['express_code']=$info['error_code'];
                    $info['express_code_desc']='创建成功';//$info['error_msg'];

                    }else {  //推送失败
                    $_result = array();
                    $_result['shop_express_no'] = $v['shop_express_no'];
                    $this->push_fail($_result, $info);

                    //for express_data
                    $info['express_code_desc'] = $info['error_data']['desc'];
                }
            }
            elseif($v['express_type'] == "jrd"){
                $JRD = new JRDExpressClass($website_array['debug'],$v['jrd_sign']);
                $info = $JRD->push_order($v);
                $log->lwrite($v['shop_express_no'].'=>jrd推送结果:'.json_encode($info, JSON_UNESCAPED_UNICODE));
                $info = array_merge($info,$sendorder_result);
                if($info && $info['error_code'] == 0){   //推送成功
                    # 推送小费
                    $where = array('AND'=>array('='=>array('order_no' => $info['result']['partner_order_no'],"isdeleted" => 0, "status" => 1)));
                    $tip_res = $this->getItemByOther($where,'tip_list');
                    $log->lwrite('查找小费信息=>' . json_encode($tip_res,JSON_UNESCAPED_UNICODE));
                    if($tip_res && count((array)$tip_res) > 0){
                        # 查找门店编号
                        $where_store = array('AND'=>array('='=>array('shop_express_no' => $info['result']['partner_order_no'], "isdeleted" => 0, "status" => 2)));
                        $store_no = $this->getItemByOther($where_store,'orders_express');
                        $log->lwrite('查找门店编号=>' . json_encode($store_no,JSON_UNESCAPED_UNICODE));


                        $where_store = array('AND'=>array('='=>array('store_id' => $store_no[0]['shop_no'], "isdeleted" => 0, "zp_status" => 1)));
                        $store_res = $this->getItemByOther($where_store,'xd_store');
                        $log->lwrite('查找门店快点参数=>' . json_encode($store_res,JSON_UNESCAPED_UNICODE));

                        $tips = 0;
                        $tipIDs = [];
                        foreach($tip_res as $k=>$t){
                            $tips += $t['price'];
                            $tipIDs[$k]['id'] = $t['id'];
                        }
                        $dde = new JRDExpressClass($website_array['debug'],$v['jrd_sign']);
                        $addFee = $dde->addTip($info['result']['order_no'],$tips);
                        $log->lwrite('小费返回信息=>' . json_encode($addFee,JSON_UNESCAPED_UNICODE));
                        if($addFee && $addFee['error_code'] == 0){
                            $tip['push_state'] = 1;
                        }else{
                            $tip['push_state'] = 9;
                        }
                        $tip['push_time'] = 'now()';
                        $tip['ret_data'] = json_encode($addFee,JSON_UNESCAPED_UNICODE);
                        foreach ($tipIDs as $v){
                            $where_fields = array("AND" => array("=" => array('id' => $v['id'], "isdeleted" => 0)));
                            $this->updateItem($tip, $where_fields, 'tip_list');
                        }
                    }


                    $_result=array();
                    $_result['shop_express_no'] = $info['result']['partner_order_no'];   # 宅配传过去
                    $_result['express_order_no'] = $info['result']['order_no']; # 第三方快递号
                    $_result['express_fee'] = $info['result']['total_price'];
                    $this->push_success($_result, $info);

                    //for express_data
                    $info['result_code'] = 0;
                    $info['express_code'] = 0;
                    $info['express_code_desc'] = $info['error_msg'];

                }else {  //推送失败
                    $_result = array();
                    $_result['shop_express_no'] = $v['shop_express_no'];
                    $this->push_fail($_result, $info);

                    //for express_data
                    $info['express_code_desc'] = $info['error_msg'];
                }

            }elseif ($v['express_type'] == "ss"){
                $sse = new SSExpressClass($website_array['debug'],$v['ss_clientId'],$v['ss_clientSecret'],$v['ss_shopId']);
                # 计价
                $info_jj = $sse->billing($v);
                $log->lwrite($v['shop_express_no'].'=>SS计价结果:'.json_encode($info_jj, JSON_UNESCAPED_UNICODE));

                # 推送计价成功 发送订单
                if($info_jj && $info_jj['status'] == 200){
                    $parameter['issOrderNo'] = $info_jj['data'][0]['issOrderNo'];                                      # 闪送订单号
                    $order_info = $sse ->send_parameter($parameter);
                    $log->lwrite($v['shop_express_no'].'=>SS推送结果:'.json_encode($order_info, JSON_UNESCAPED_UNICODE));

                    $info = array_merge($order_info,$sendorder_result);
                    if($order_info && $order_info['status'] == 200){
                        # 对接小费
                        $_result=array();
                        $_result['shop_express_no'] = $order_info['data'][0]['orderNoList'][0]['orderNo'];          # 派单单号
                        $_result['express_order_no'] = $order_info['data'][0]['issOrderNo'];                        # 快递订单单号
                        $_result['express_fee'] = $order_info['data'][0]['totalFee']/100;      # 费用
                        $this->push_success($_result, $order_info);

                        //for express_data
                        $info['result_code'] = 0;
                        $info['express_code'] = $order_info['status'];
                        $info['express_code_desc'] = '下单成功';
                    }else{
                        $_result = array();
                        $_result['shop_express_no'] = $v['shop_express_no'];
                        $this->push_fail($_result, $info);

                        //for express_data
                        $info['express_code_desc'] = $order_info['msg'];
                        $info['result_code'] = 1;
                        $info['express_code'] = $order_info['status'];
                    }


                }else {  //推送失败
                    $_result = array();
                    $info = array_merge($info_jj,$sendorder_result);
                    $_result['shop_express_no'] = $v['shop_express_no'];
                    $this->push_fail($_result, $info);

                    //for express_data
                    $info['express_code_desc'] = $info_jj['msg'];
                    $info['result_code'] = 1;
                    $info['express_code'] = $info_jj['status'];
                }


            }elseif($v['express_type'] == "dd"){
                $dde = new DDExpressClass($website_array['debug'],$v['dd_source_id'],$v['dd_app_key'],$v['dd_app_secret']);
                $info = $dde->send_parameter($v);
                $log->lwrite($v['shop_express_no'].'=>DD推送结果:'.json_encode($info, JSON_UNESCAPED_UNICODE));

                if($info && $info['status'] == 'success'){   //推送成功
                    $_result = array();
                    $_result['shop_express_no'] = $v['shop_express_no'];        # 达达不返 快点单号 和门店订单号
                    $_result['express_order_no'] = $v['shop_express_no'];
                    $_result['express_fee'] = $info['result']['deliverFee'];
                    $this->push_success($_result, $info);

                    //for express_data
                    $info['result_code'] = 0;
                    $info['express_code'] = $info['code'];
                    $info['express_code_desc'] = $info['msg'];

                }else {  //推送失败
                    if($info == false){
                        //for express_data
                        $info['express_code_desc'] = '达达请求返回：false';
                    }else{
                        //for express_data
                        $info['express_code_desc'] = $info['msg'];
                    }
                    $info=array_merge($info,$sendorder_result);

                    $_result = array();
                    $_result['shop_express_no'] = $v['shop_express_no'];
                    $this->push_fail($_result, $info);
                }

            }elseif($v['express_type'] == "uu"){
                $dde = new DDExpressClass($website_array['debug'],$v['dd_source_id'],$v['dd_app_key'],$v['dd_app_secret']);
                $info = $dde->send_parameter($v);
                $log->lwrite($v['shop_express_no'].'=>DD推送结果:'.json_encode($info, JSON_UNESCAPED_UNICODE));

                if($info && $info['status'] == 'success'){   //推送成功
                    $_result = array();
                    $_result['shop_express_no'] = $v['shop_express_no'];        # 达达不返 快点单号 和门店订单号
                    $_result['express_order_no'] = $v['shop_express_no'];
                    $_result['express_fee'] = $info['result']['deliverFee'];
                    $this->push_success($_result, $info);

                    //for express_data
                    $info['result_code'] = 0;
                    $info['express_code'] = $info['code'];
                    $info['express_code_desc'] = $info['msg'];

                }else {  //推送失败
                    if($info == false){
                        //for express_data
                        $info['express_code_desc'] = '达达请求返回：false';
                    }else{
                        //for express_data
                        $info['express_code_desc'] = $info['msg'];
                    }
                    $info=array_merge($info,$sendorder_result);

                    $_result = array();
                    $_result['shop_express_no'] = $v['shop_express_no'];
                    $this->push_fail($_result, $info);
                }

            }else{
               echo 'self';
            }
            $this->updateExpressData($data_id, $info);
        }
    }


    public function push_success($_result, $info){

        if(!empty($_result['express_order_no'])){  # 订单创建成功
            $where = array("AND" => array("=" => array('shop_express_no' => $_result['shop_express_no'], "status"=>1,"isdeleted"=>0)));
            $orderInfo = $this->getItemByOther($where,'orders_express');
            if(!empty($orderInfo)){
                //更新指派订单和订单的状态
                $columns=array();
                $columns['push_response_data'] =  json_encode($info,JSON_UNESCAPED_UNICODE);
                $columns['express_order_no'] = $_result['express_order_no'];
                $columns['express_fee'] = $_result['express_fee'];
                $columns['status'] = 2;

                $OrderColumns=array();
                $OrderColumns['status'] = 2;
                $where = array("AND" => array("=" => array("ph_no"=>$orderInfo[0]['ph_no'],"status" => 1,"isdeleted" => 0)));
                $this->updateItem($OrderColumns,$where,'orders');
            }else {
                $columns['status'] = 0;  //推送失敗
                $columns['push_response_data'] =  json_encode($_result,JSON_UNESCAPED_UNICODE);

            }

            $where = array("AND" => array("=" => array("shop_express_no"=>$_result['shop_express_no'],"status" => 1,"isdeleted" => 0)));
            $this->updateItem($columns,$where,'orders_express');
        }

    }


    public function push_fail($_result, $info){
            $columns=array();
        $columns['status'] = 0;  //推送失敗
        $columns['push_response_data'] = json_encode($info,JSON_UNESCAPED_UNICODE);

        $where = array("AND" => array("=" => array("shop_express_no"=>$_result['shop_express_no'],"status" => 1,"isdeleted" => 0)));
        $this->updateItem($columns,$where,'orders_express');
    }



    # 仅推送二天内的订单给快递
    public function GetExpressOrders() {
        $shop_no = $_SESSION['zp_shop']['store_id'];
        $lastDay = date('Y-m-d H:i:s',strtotime('+2 day'));
        $sql = " SELECT * FROM orders_express WHERE isdeleted = 0 AND status = 1 AND shop_no = $shop_no AND shop_pickup_time <= '$lastDay'";
//        $sql = " SELECT * FROM orders_express WHERE isdeleted = 0 AND status = 1 AND shop_no = $shop_no AND express_type = 'jrd' AND shop_pickup_time <= '$lastDay'";
        $this->db->setStatement($sql);
        $result= $this->db->execute();
        $result=$this->getArray($result);
        return $result;
    }

}